package cn.mayaslight.wechat.springbean;

import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import cn.mayaslight.common.utils.SyncUtils;
import cn.mayaslight.wechat.api.TokenAPI;
import cn.mayaslight.wechat.api.bean.Token;
import cn.mayaslight.wechat.common.WeChatConsts;

@Component
public class TokenGetter {

	@Resource
	private RedisTemplate<String, String> redisTemplate;
	
	private static Object LOCK = new Object();

	private static TokenGetter instance = null;
	
	@Value("APP_ID")
	private String appId;
	
	@Value("APP_SECRET")
	private String appSecret;
	
	@Value("IS_QY")
	private boolean isQy;
	
	private TokenGetter() {
		
	}
	
	public static TokenGetter getInstance () {
		instance = SyncUtils.sync(instance, TokenGetter.class, LOCK);
		return instance;
	}
	
	@PostConstruct
	public void init() {
		instance = this;
	}
	
	public String get() {
		String tokenStr = redisTemplate.opsForValue().get(WeChatConsts.RedisKeys.RES_ACCESS_TK_KEY_PRE + appId);
		if(StringUtils.isEmpty(tokenStr)){
			synchronized(this){
				tokenStr = redisTemplate.opsForValue().get(WeChatConsts.RedisKeys.RES_ACCESS_TK_KEY_PRE + appId);
				if(StringUtils.isEmpty(tokenStr)){
					Token token = null;
					token = TokenAPI.token(appId, appSecret, isQy);
					tokenStr = token.getAccess_token();
					redisTemplate.opsForValue().set(WeChatConsts.RedisKeys.RES_ACCESS_TK_KEY_PRE + appId, token.getAccess_token(), WeChatConsts.Constants.RES_TOKEN_AND_TICKET_EXPIRE_SECOND, TimeUnit.SECONDS);
				}
			}
		}
		return tokenStr;
	}
	
	public String get(String corpid, String secret, boolean isQyHao) {
		String tokenStr = redisTemplate.opsForValue().get(WeChatConsts.RedisKeys.RES_ACCESS_TK_KEY_PRE + corpid);
		if(StringUtils.isEmpty(tokenStr)){
			synchronized(this){
				tokenStr = redisTemplate.opsForValue().get(WeChatConsts.RedisKeys.RES_ACCESS_TK_KEY_PRE + corpid);
				if(StringUtils.isEmpty(tokenStr)){
					Token token = null;
					token = TokenAPI.token(corpid, secret, isQyHao);
					tokenStr = token.getAccess_token();
					redisTemplate.opsForValue().set(WeChatConsts.RedisKeys.RES_ACCESS_TK_KEY_PRE + corpid, token.getAccess_token(), WeChatConsts.Constants.RES_TOKEN_AND_TICKET_EXPIRE_SECOND, TimeUnit.SECONDS);
				}
			}
		}
		return tokenStr;
	}

	public RedisTemplate<String, String> getRedisTemplate() {
		return redisTemplate;
	}

	public TokenGetter setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
		this.redisTemplate = redisTemplate;
		return this;
	}
	
}
